//
//  MyNetWorkTool.swift
//  weibo08
//
//  Created by 陈杰明 on 16/2/28.
//  Copyright © 2016年 JM. All rights reserved.
//

import UIKit
import AFNetworking

//值类型
enum MyNetWorkToolError: Int {
    case AccessTokenEmpty = -1
    case UidEmpty = -2
    //枚举属性
    var errorMessage: String {
        get{
            switch self {
            case AccessTokenEmpty: return "accesstoken没有值"
            case UidEmpty: return "uid没有值"
            }
        }
    }
    //枚举方法
    func error() -> NSError {
        return NSError(domain: "my.net", code: self.rawValue, userInfo: ["errorMessage" : self.errorMessage])
    }
}

class MyNetWorkTool: NSObject {

    
    let AFNManager: AFHTTPSessionManager
    
    //单例
    static let sharedInstance: MyNetWorkTool = MyNetWorkTool()
    
    private override init(){
        
        let baseUrl = NSURL(string: "https://api.weibo.com/")
        
        AFNManager = AFHTTPSessionManager(baseURL: baseUrl)
        
        AFNManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
        
    }
    
    //MARK: - Oauth授权相关
    let client_id = "250759251"
    let client_secret = "fee263d5870c20d45ba084a35ec1f500"
    let redirect_uri = "http://www.baidu.com/"
    let oauthURL = "https://api.weibo.com/oauth2/authorize"
    
    func oauthLogin() -> NSURL {
    
        //获取登录授权的地址
        let urlStr = oauthURL + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        let url = NSURL(string: urlStr)
        
        return url!
        
    }
    //获取accessToken
    func loadAccessToken(code : String, accessTokenFinished: finishedCallBack) {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
    AFNManager.POST(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        //response转成字典
        let dict = result as? [String: AnyObject]
        accessTokenFinished(result: dict, error: nil)
        
        }) { (_, error) -> Void in
            
          accessTokenFinished(result: nil, error: error)
        }
}
    
    func loadUserInfo(finished: finishedCallBack) {
        //获取accesstoken
//        let access_token = MyUserAccountViewModel.sharedInstance.userAccount?.access_token

        //守卫
//        MyUserAccountViewModel.sharedInstance.userAccount?.access_token = nil
        guard let uid = MyUserAccountViewModel.sharedInstance.userAccount?.uid else {
//            print("uid没有值")
//            let errorEnum = MyNetWorkToolError.UidEmpty
//            let error = NSError(domain: "my.net", code: errorEnum.rawValue, userInfo: ["errorMessage" : errorEnum.errorMessage])
            let error = MyNetWorkToolError.UidEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let parameters = [
            "uid" : uid
        ]
        //请求
//        AFNManager.GET(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            print("result:\(result)")
//            finished(result: result as! [NSString: AnyObject]?, error: nil)
//            }) { (_, error) -> Void in
//            print("error:\(error)")
//            finished(result: nil, error: error)
//        }
        self.requestUrl(urlStr, parameters: parameters, finished: finished)
    }
    //微博数据加载
    func loadStatus(finished: finishedCallBack) {
    
        let urlStr = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
//        let parameters = [ "access_token" : access_token]
        
//        AFNManager.GET(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
//            print("result:\(result)")
//            finished(result: result as! [NSString: AnyObject]?, error: nil)
//            }) { (_, error) -> Void in
//            print("error:\(error)")
//            finished(result: nil, error: error)
//        }
        self.requestUrl(urlStr, parameters: nil, finished: finished)
    }
    //定义闭包
    typealias finishedCallBack = (result: [String: AnyObject]?, error: NSError?) -> ()
    //抽取网络请求
    private func requestUrl(urlStr: String, var parameters: [String : AnyObject]?, finished: finishedCallBack) {
    
        guard let access_token = MyUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            let error = MyNetWorkToolError.AccessTokenEmpty.error()
            finished(result: nil, error: error)
            return
        }
        if parameters == nil {
            parameters = [String : AnyObject]()
        }
        
        parameters!["access_token"] = access_token
        
        //get方法
        AFNManager.GET(urlStr, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            print("result:\(result)")
            finished(result: result as! [String: AnyObject]?, error: nil)
            }) { (_, error) -> Void in
                print("error:\(error)")
                finished(result: nil, error: error)
        }
    
    }
}
        